#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtCore, QtGui
from xml.dom import minidom
import xml.parsers.expat
from Ui_dialog_login import *
from libASFX import *

#source on the web: http://quilovnic.developpez.com/pythondom/

class Database:
    name = None
    host = None
    user = None
    pwd = None
    def __init__(self):
        pass

class TransformXmlToDatabases:
    __currentNode__ = None
    __databaseList__ = None

    def __init__(self,file):
        self.readXml(file)

    def readXml(self,file):
        try:
            fsock = open(file)
            self.doc = minidom.parse(fsock) 
            fsock.close()
        except IOError,e:
            QtGui.QMessageBox.warning(self,"Error reading config.xml file: ",QtCore.QString(str(e)))
            return
        except xml.parsers.expat.ExpatError, e:
            QtGui.QMessageBox.warning(self,"Error parsing config.xml file: ",QtCore.QString(str(e)))
            return

    def getRootElement(self):
        if self.__currentNode__ == None:
            self.__currentNode__ = self.doc.documentElement
        return self.__currentNode__

    def getText(self, node):
        return node.childNodes[0].nodeValue
    
    def getDatabases(self):
        if self.__databaseList__ != None:
            return 

        self.__databseList__ = []
        errors = 0
        for databases in self.getRootElement().getElementsByTagName("Database"):
            if databases.nodeType == databases.ELEMENT_NODE:
                d = Database()
                try:
                    d.name = self.getText(databases.getElementsByTagName("name")[0])
                    d.host = self.getText(databases.getElementsByTagName("host")[0])
                    d.access_mode = self.getText(databases.getElementsByTagName("access_mode")[0])
                    d.user = self.getText(databases.getElementsByTagName("user")[0])
                    d.pwd = self.getText(databases.getElementsByTagName("pwd")[0])
                except:
                    #QtGui.QMessageBox.warning(self, "myCF Error",unicode("You've just created the same relation."))
                    errors +=1

                self.__databseList__.append(d)
        print("incomplete data(s) for %d profile(s) in config.xml"%errors)
        return self.__databseList__


class Dialog_login(QtGui.QDialog, Ui__Dialog_login):
    
    def __init__(self,parent):
        super(Dialog_login,self).__init__(parent) 
        self.setupUi(self)
        
        #Read the config file and populate the comboBox_name
        if sys.platform.startswith('linux'):
            print 'linux'
            self.databases=TransformXmlToDatabases('../../config.xml').getDatabases()
        if sys.platform.startswith('win'):
            print 'windows'
            self.databases=TransformXmlToDatabases('../../config.xml').getDatabases()
        self.populate_comboBox_name()
    
    def populate_comboBox_name(self):    
        for d in self.databases:
            self.comboBox_name.addItem(QtCore.QString(d.name))
    
    @QtCore.pyqtSignature("int")
    def on_comboBox_name_currentIndexChanged(self,index):
        self.lineEdit_host.clear()
        self.lineEdit_user.clear()
        self.lineEdit_pwd.clear()
        if self.databases[index].host:
            self.lineEdit_host.setText(QtCore.QString(self.databases[index].host))
        if self.databases[index].user:
            self.lineEdit_user.setText(QtCore.QString(self.databases[index].user))
        if self.databases[index].pwd:
            self.lineEdit_pwd.setText(QtCore.QString(self.databases[index].pwd))
        
        try :
            if self.databases[index].access_mode :
                if self.databases[index].access_mode == "read":
                    self.QCheckBox_access_mode.setCheckState(QtCore.Qt.Checked)
                    self.QCheckBox_access_mode.setEnabled(False) 
                else :
                    if self.databases[index].access_mode == "write":
                        self.QCheckBox_access_mode.setCheckState(QtCore.Qt.Unchecked)
                        self.QCheckBox_access_mode.setEnabled(True)
                    else :
                        self.QCheckBox_access_mode.setCheckState(QtCore.Qt.Checked)
                        self.QCheckBox_access_mode.setEnabled(True) 
        except :
            self.QCheckBox_access_mode.setCheckState(QtCore.Qt.Checked)
            self.QCheckBox_access_mode.setEnabled(True)
            
            error_message = "Error while reading access mode for this profile, You may have to update your \'config.xml\' file. \
            \nYou should not leave an empty field for the access mode."
            QtGui.QMessageBox.information(self, "No access mode defined",unicode(error_message))

        
            
    @QtCore.pyqtSignature("")
    def on_buttonBox_accepted(self):
        
        if self.QCheckBox_access_mode.isChecked() :
            access_mode = "read"
        else :
            access_mode = "write" 
        
        self.sqlserver = db.SQlserver( unicode(self.lineEdit_host.text()).encode('utf-8'),   unicode(self.lineEdit_user.text()).encode('utf-8'),  unicode(self.lineEdit_pwd.text()).encode('utf-8'), access_mode)
        test = self.sqlserver.test_connection()
        if test == True:
            QtGui.QDialog.accept(self)
        else:
            info= "The connection to SQL Database doesn't work.\n Please check your internet connection and/or logins.\n "+str(self.sqlserver.error)
            QtGui.QMessageBox.warning(self,"myCF Error Connection",info)
            self.reject()
    
    @QtCore.pyqtSignature("")
    def on_buttonBox_rejected(self):
        self.reject()